package util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.List;

public class JsonUtil {
    public static String writeValueAsString(Object o) throws JsonProcessingException {
        ObjectMapper objectMapper=new ObjectMapper();
        return objectMapper.writeValueAsString(o);
    }
    //输入一个属性名和值获得json对象格式的字符串
    public static String stringValueToJson(String valueName,String value){
        return "{\""+valueName+"\":\""+value+"\"}";
    }
    public static String ordinaryValueToJson(String valueName,String value){
        return "{\""+valueName+"\":"+value+"}";
    }
    //输入多个属性名和值获得json对象格式的字符串
    public static String valuesToJson(String[] valueName,String[] value){
        StringBuilder sb=new StringBuilder();
        sb.append("{");
        for(int i=0;i<valueName.length-1;i++){
            sb.append("\""+valueName[i]+"\":");
            sb.append("\""+value[i]+"\",");
        }
        sb.append("\""+valueName[valueName.length-1]+"\":");
        sb.append("\""+value[value.length-1]+"\"}");
        return sb.toString();
    }
    public static String stringListToJson(String listName,String valueName,List<String> list){
        StringBuilder sb=new StringBuilder();
        sb.append("{\""+listName+"\":[");
        for(int i=0;i<list.size()-1;i++){
            String s=list.get(i);
            sb.append("{\""+valueName+"\":");
            sb.append("\""+s+"\"},");
        }
        sb.append("{\""+valueName+"\":");
        sb.append("\""+list.get(list.size()-1)+"\"}");
        sb.append("]}");
        return sb.toString();
    }
}
